package com.xms.schema.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xms.core.model.PagedList;
import com.xms.schema.core.AttributeDefaults;
import com.xms.schema.core.EntityMask;
import com.xms.schema.entity.Attribute;
import com.xms.schema.entity.Entity;
import com.xms.schema.service.attribute.IAttributeFinderService;
import com.xms.schema.service.attribute.IAttributeUnionFinderService;
import com.xms.schema.service.attribute.IDefaultAttributeProvider;
import com.xms.utils.CollectionUtil;
import com.xms.utils.StringUtil;
import com.xms.utils.UUIDUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * <p>
 * AttributeMetadataController
 * </p>
 *
 * @author migo
 * @since 2021/9/8
 */
@RestController
@RequestMapping("{org}/api/schema/attribute")
public class AttributeFinderController extends ApiBaseController {
    private IAttributeFinderService _attributeFinderService;
    private IAttributeUnionFinderService _attributeUnionFinderService;
    private IDefaultAttributeProvider _defaultAttributeProvider;
    @Autowired
    public void AttributeMetadataController(IAttributeFinderService attributeFinderService,
                                            IDefaultAttributeProvider defaultAttributeProvider,
                                            IAttributeUnionFinderService attributeUnionFinderService) {
        _attributeFinderService = attributeFinderService;
        _defaultAttributeProvider = defaultAttributeProvider;
        _attributeUnionFinderService = attributeUnionFinderService;
    }

    @ApiOperation("实体字段列表")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public JsonResultObject get(@RequestParam(name="attributetypename", required = false) String attributeTypeName,
                                @RequestParam(name="name", required = false) String name,
                                @RequestParam(name="entityid", required = false) UUID entityId,
                                @RequestParam(name="filtersysattribute", required = false) Boolean filterSysAttribute,
                                @RequestParam(name="getall", required = false) Boolean getall,
                                @RequestParam(name="page", required = false) Integer page,
                                @RequestParam(name="pagesize", required = false) Integer pagesize,
                                @RequestParam(value="sortby", required = false) String sortby,
                                @RequestParam(value="sortdirection", required = false) String sortdirection)
    {
        if (UUIDUtil.isEmpty(entityId))
        {
            return JNotSpecifiedParams("entityid");
        }
        LambdaQueryWrapper<Attribute> lambdaQueryWrapper = getSortedQueryWrapper(sortby, sortdirection);;
        if(UUIDUtil.notEmpty(entityId)) {
            lambdaQueryWrapper.eq(Attribute::getEntityid, entityId);
        }
        if (StringUtil.notEmpty(attributeTypeName))
        {
            String[] names = StringUtil.splitSafe(attributeTypeName, ",");
            lambdaQueryWrapper.in(Attribute::getAttributetypename, names);
        }
        if (StringUtil.notEmpty(name))
        {
            lambdaQueryWrapper.like(Attribute::getName, name);
        }
        if (filterSysAttribute != null && filterSysAttribute){
            lambdaQueryWrapper.notIn(Attribute::getName, AttributeDefaults.SYSTEM_ATTRIBUTES);
        }
        if (getall != null && getall) {
            return JOk(_attributeFinderService.list(lambdaQueryWrapper));
        }
        else if(page == null || pagesize == null){
            return JNotSpecifiedParams("page","pagesize");
        }
        page = (page <= 0 ? 1 : page);
        pagesize = (pagesize <= 0 ? 10 : pagesize);
        IPage<Attribute> datas = _attributeFinderService.page(new Page<>(page, pagesize), lambdaQueryWrapper);
        PagedList<Attribute> result = new PagedList<>(page, pagesize, datas.getTotal());
        result.items = datas.getRecords();
        result.totalpages = datas.getPages();
        return JOk(result);
    }

    @ApiOperation("字段名称是否存在")
    @GetMapping("exists")
    public JsonResultObject exists(@RequestParam(value="entityid",required = true) UUID entityid,
                                   @RequestParam(value="name",required = true) String name){
        if(_attributeFinderService.getByName(entityid, name) != null)
        {
            return JOk();
        }
        return JsonResultObject.failure("", 200);
    }

    @ApiOperation("查询字段元数据")
    @GetMapping("getbyid/{id}")
    public JsonResultObject getById(@PathVariable(value="id", required = true) UUID id)
    {
        Attribute attribute = _attributeUnionFinderService.getById(id);
        return JOk(attribute);
    }

    @ApiOperation("查询字段元数据")
    @RequestMapping(value = "getbyentityid/{entityid}", method = RequestMethod.GET)
    public JsonResultObject get(@PathVariable(value = "entityid", required = true) UUID entityid,
                                @RequestParam(value = "name", required = false) String name)
    {
        if (name.isEmpty())
        {
            return JOk(_attributeUnionFinderService.getByEntityId(entityid));
        }
        else
        {
            return JOk(_attributeUnionFinderService.getByName(entityid, name));
        }
    }

    @ApiOperation("查询字段元数据")
    @RequestMapping(value = "getbyentityname/{entityname}", method = RequestMethod.GET)
    public JsonResultObject get(@PathVariable(value = "entityname", required = true) String entityname,
                                @RequestParam(value = "name", required = false) String name)
    {
        if (StringUtil.isEmpty(name))
        {
            return JOk(_attributeUnionFinderService.getByEntityName(entityname));
        }
        else
        {
            return JOk(_attributeUnionFinderService.getByName(entityname, name));
        }
    }

    @ApiOperation("获取系统标准字段")
    @RequestMapping(value = "systemattributes/{entitymask}", method = RequestMethod.GET)
    public JsonResultObject getSystemAttributes(@PathVariable(value = "entitymask", required = true) EntityMask entityMask)
    {
        Entity entity = new Entity();
        entity.setWorkflowenabled(true);
        entity.setEntitymask(entityMask.value());
        return JOk(_defaultAttributeProvider.getSysAttributes(entity).attributes);
    }
}
